package com.tieshu.matissecrop.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.zhihu.matisse.Matisse;

import java.io.File;

public class PicCrop {
    public static final int REQUEST_SELECT_PICTURE = 0x01;
    private static final int REQUEST_CAMERA = 0x03;
    private static final String EXTRA_VIEW_TAG = "viewTag";

    public static final int TYPE_AVATAR = 1;
    public static final int TYPE_NORMAL = 2;

    public static Uri getUri() {
        return uri;
    }

    private static Uri uri;

    private static CropConfig config = new CropConfig();


    private static Uri buildUri(Activity context) {

        String filepath = context.getCacheDir().getPath() + "/" + "crop";

        String name = String.format("imagecrop_%d.jpg", System.currentTimeMillis());
        if (!isFileExist(filepath)) {
            createFolder(filepath);
        }

        File file = new File(filepath, name);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, "com.tieshu.matissecrop.FileProvider", file);
            return uri;
        } else {
            uri = Uri.fromFile(file);
            return uri;

        }
    }

    /**
     * 新建目录
     *
     * @param path 目录的绝对路径
     * @return 创建成功则返回true
     */
    public static boolean createFolder(String path) {
        File file = new File(path);
        return file.mkdirs();
    }

    /**
     * 判断文件是否已经存在
     *
     * @param fileName 要检查的文件名
     * @return boolean, true表示存在，false表示不存在
     */
    public static boolean isFileExist(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }

    public static void cropFromMatisse(int type) {
        if (config != null) {
            PicCrop.config = config;
        } else {
            PicCrop.config = new CropConfig();
        }

        setType(type);
    }

    public static void cropAvatarFromGallery(Activity context) {
        cropFromGallery(context, null, TYPE_AVATAR);
    }

    public static void cropAvatarFromCamera(Activity context) {
        cropFromCamera(context, null, TYPE_AVATAR);
    }


    public static void cropFromGallery(Activity context, CropConfig config, int type) {
        if (config != null) {
            PicCrop.config = config;//怎么避免前后两次config
        } else {
            PicCrop.config = new CropConfig();
        }

        setType(type);

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        context.startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_SELECT_PICTURE);
    }

    private static void setType(int type) {
        if (type == TYPE_AVATAR) {
            config.isOval = true;
            config.aspectRatioX = 1;
            config.aspectRatioY = 1;
            config.hideBottomControls = true;
            config.showGridLine = false;
            config.showOutLine = false;
            config.maxHeight = 500;
            config.maxWidth = 500;
        } else if (type == TYPE_NORMAL) {//什么都不用做


        } else {

        }
    }

    public static void cropFromCamera(Activity context, CropConfig config, int type) {
        if (config != null) {
            PicCrop.config = config;
        } else {
            PicCrop.config = new CropConfig();
        }

        setType(type);
        Uri mDestinationUri = buildUri(context);
        //调用系统相机
        Intent intentCamera = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //将拍照结果保存至photo_file的Uri中，不保留在相册中
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, mDestinationUri);
        context.startActivityForResult(intentCamera, REQUEST_CAMERA);
    }

    public static void cropFromGallery(Activity context) {

        cropFromGallery(context, null, 0);
    }

    public static void cropFromCamera(Activity context) {
        cropFromCamera(context, null, 0);
    }

    /**
     * 注意，调用时data为null的判断
     *
     * @param context
     * @param cropHandler
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public static void onActivityResult(int requestCode, int resultCode, Intent data, Activity context, CropHandler cropHandler) {

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_SELECT_PICTURE) {
                //第一次，选择图片后返回
                Uri selectedUri = null;
                if (data != null) {
                    selectedUri = Matisse.obtainResult(data).get(0);
                }
                if (selectedUri != null) {
                    startCropActivity(context, selectedUri);
                } else {
                    Toast.makeText(context, "Cannot retrieve selected image", Toast.LENGTH_SHORT).show();
                }
            } else if (requestCode == UCrop.REQUEST_CROP) {
                //第二次返回，图片已经剪切好
                Uri finalUri = UCrop.getOutput(data);
                cropHandler.handleCropResult(finalUri, config.tag);

            } else if (requestCode == REQUEST_CAMERA) {
                //第一次，拍照后返回，因为设置了MediaStore.EXTRA_OUTPUT，所以data为null，数据直接就在uri中
                startCropActivity(context, uri);
            }
        }
        if (resultCode == UCrop.RESULT_ERROR) {
            cropHandler.handleCropError(data);
        }

    }


    private static void startCropActivity(Activity context, Uri sourceUri) {
        Uri mDestinationUri = buildUri(context);
        UCrop uCrop = UCrop.of(sourceUri, mDestinationUri);
        Log.e("picpic", "mDestinationUri=: " + mDestinationUri);
        uCrop.withAspectRatio(config.aspectRatioX, config.aspectRatioY);
        uCrop.withMaxResultSize(config.maxWidth, config.maxHeight);

        UCrop.Options options = new UCrop.Options();
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.NONE, UCropActivity.NONE);
//        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        options.setCompressionQuality(config.quality);
        // options.setOvalDimmedLayer(config.isOval);
        options.setCircleDimmedLayer(config.isOval);
        options.setShowCropGrid(config.showGridLine);
        options.setHideBottomControls(config.hideBottomControls);
        options.setShowCropFrame(config.showOutLine);
        options.setToolbarTitle("自定义裁剪");
        options.setToolbarWidgetColor(Color.WHITE);

        options.setToolbarColor(Color.BLUE);
        options.setStatusBarColor(Color.BLUE);

        uCrop.withOptions(options);

        uCrop.start(context);
    }


    public static class CropConfig {
        public int aspectRatioX = 2;
        public int aspectRatioY = 1;
        public int maxWidth = 1080;
        public int maxHeight = 1920;

        //options
        public int tag;
        public boolean isOval = false;//是否为椭圆
        public int quality = 80;

        public boolean hideBottomControls = true;//底部操作条
        public boolean showGridLine = true;//内部网格
        public boolean showOutLine = true;//最外面的矩形线


        public void setAspectRation(int x, int y) {
            this.aspectRatioX = x;
            this.aspectRatioY = y;
        }

        public void setMaxSize(int width, int height) {
            this.maxHeight = height;
            this.maxWidth = width;
        }

    }


    public interface CropHandler {
        void handleCropResult(Uri uri, int tag);

        void handleCropError(Intent data);
    }

}